<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'

import {
  useMessage,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NPopconfirm,
  NTreeSelect,
  NTag,
  NSwitch,
  NFlex,
  NAvatar,
  NSelect,
  NImage,
     NDataTable
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import { getToken } from '@/utils'
import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'

defineOptions({ name: '报销审核' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE
import default_image from '@/assets/images/mz.jpg'
const message = useMessage()
const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '报销审核',
  initForm: {},
  doCreate: api.createBaoXiao,
  doUpdate: api.checkBaoXiao,
  doDelete: api.deleteBaoXiao,
  refresh: () => $table.value?.handlerefresh(),
})
const isDisabled = ref(false)
const data = reactive({
  xms:[],
  users:[],
  uploadAction: base_path + 'api/baoxiao/baoxiao_list/file',
  token: getToken(),
  state_option: [
      {
    value:0,
    label:"待审核"
  },{
    value:1,
    label:"已审核"
  },{
    value:2,
    label:"驳回"
  }],
  check_option: [
   {
    value:1,
    label:"通过"
  },{
    value:2,
    label:"驳回"
  }],

})
const deptOption = ref([])

onMounted(() => {
  api.getBaoXiaoXms().then((res) => (data.xms = res.data))
  api.getUsers().then((res) => (data.users = res.data))
  api.getDeptsTree().then((res) => (deptOption.value = res.data))
  $table.value?.handleSearch()
})

async function addDepts() {
  isDisabled.value = false
  handleAdd()
}

const columns = [
    {
    title: '+',
    width: 60,
    key: 'details',
    align: 'center',
    type: 'expand',
    expandable: (row) => row.details !== null,
    renderExpand: (row) => {
      let details = row.details ?? []
      let details_columns = [
          {
          width: 'auto',
          title: '日期',
          key: 'add_date',
        },
        {
          width: 'auto',
          title: '项目',
          key: 'xm_name',
        },
          {
          width: 'auto',
          title: '金额',
          key: 'price',
        },{
          width: 'auto',
          title: '发票金额',
          key: 'fp_price',
        },
           {
          width: 'auto',
          title: '备注',
          key: 'desc',
        },
        {
          width: '80',
          title: '发票',
          key: 'pic1',
          render(row2) {
            let image = row2.pic1[0]
            if (!image) {
              image = default_image
            }
            return h(NFlex, {}, [
              h(NImage, {
                src: image.url,
                width: 30,
                fallbackSrc: default_image,
                style: {
                  borderRadius: '5px'  // 使图片变为圆形
                }
              }),
            ])
          },
        },

        {
        width: "auto",
        title: '凭证',
        key: 'pic2',
        render(row2) {
          let images = row2.pic2 || [];  // 如果没有 pic1 数据，默认为空数组
          if (images.length === 0) {
            images = [default_image];  // 如果没有图片，使用默认图片
          }
          // 渲染图片
          return h(NFlex, { wrap: 'wrap' },  // 使用 wrap: 'wrap' 让图片能够换行显示
            images.map(image =>
              h(NImage, {
                src: image.url || default_image,  // 如果图片地址为空，则使用默认图片
                width: 30,  // 图片的宽度
                height: 30, // 图片的高度
                fallbackSrc: default_image,  // 加载失败时使用的默认图片
                style: {
                  borderRadius: '2px',  // 圆角样式
                }
              })
            )
          );
        },
      }


      ]
      return h(NDataTable, {
        columns: details_columns,
        striped: true,
        size: 'small',
        data: details,
        style: { width: '1000px', margin: '10px 10px' },
      })
    },
  },
  {
    title: 'ID',
    key: 'id',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '报销部门',
    key: 'bm_name',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },
    {
    title: '报销人',
    key: 'user_name',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },
  {
    title: '单号',
    key: 'no',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },{
    title: '报销金额',
    key: 'price',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  }, {
    title: '发票金额',
    key: 'fp_price',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  }, {
    title: '发票差额',
    key: 're_price',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },

  {
    title: '状态',
    key: 'status_name',
    width: '100',
    align: 'center',
    fixed: 'right',
    render(row) {
      return h(
        NTag,
        { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
        { default: () => row.status_name }
      )
    },

  },
  {
    title: '创建时间',
    key: 'created_at',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
  },
  {
    title: '操作',
    key: 'actions',
    width: 'auto',
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                handleEdit(row)
              },
            },
            {
              default: () => '审核',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          [[vPermission, 'post/api/baoxiao/baoxiao_list/update']]
        ),

      ]
    },
  },
]
const details_columns = [
    {
          width: '120',
          title: '日期',
          key: 'add_date',
        },
        {
          width: '80',
          title: '项目',
          key: 'xm_name',
        },
          {
          width: '80',
          title: '报销',
          key: 'price',
        }, {
          width: '80',
          title: '发票',
          key: 'fp_price',
        },
           {
          width: 'auto',
          title: '备注',
          key: 'desc',
        },
        {
          width: '80',
          title: '发票',
          key: 'pic1',
          render(row2) {
            let image = row2.pic1[0]
            if (!image) {
              image = default_image
            }
            return h(NFlex, {}, [
              h(NImage, {
                src: image.url,
                width: 30,
                fallbackSrc: default_image,
                style: {
                  borderRadius: '5px'  // 使图片变为圆形
                }
              }),
            ])
          },
        },
        {
        width: "160",
        title: '凭证',
        key: 'pic2',
        render(row2) {
          let images = row2.pic2 || [];  // 如果没有 pic1 数据，默认为空数组
          if (images.length === 0) {
            images = [default_image];  // 如果没有图片，使用默认图片
          }
          // 渲染图片
          return h(NFlex, { wrap: 'wrap' },  // 使用 wrap: 'wrap' 让图片能够换行显示
            images.map(image =>
              h(NImage, {
                src: image.url || default_image,  // 如果图片地址为空，则使用默认图片
                width: 30,  // 图片的宽度
                height: 30, // 图片的高度
                fallbackSrc: default_image,  // 加载失败时使用的默认图片
                style: {
                  borderRadius: '2px',  // 圆角样式
                }
              })
            )
          );
        },
      }


      ]
const validateAddUser = {
  name: [
    {
      required: true,
      message: '请输入报销项目名称',
      trigger: ['input', 'blur', 'change'],
    },
  ],
}

const datetimeRange = ref()
function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}

const onCreate_gg = () => {
  return {
    xm_id: 1,
    price: '',
    desc: '',
    pic1: [],
    pic2: [],
  }
}
const handleFinish = ({ file, event }) => {
  let data = (event?.target).response
  data = JSON.parse(data)
  console.log(data)
  if (data.code === 200) {
    file.url = data.data.url
    message.success('上传成功')
  } else {
    message.error(data.data)
  }

  return file
}
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="报销审核">
    <template #action>
<!--      <div>-->
<!--        <NButton-->
<!--          v-permission="'post/api/mini/settings/create'"-->
<!--          class="float-right mr-15"-->
<!--          type="primary"-->
<!--          @click="addDepts"-->
<!--        >-->
<!--          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />-->
<!--          填写报销单-->
<!--        </NButton>-->
<!--      </div>-->
    </template>
    <!-- 表格 -->
    <CrudTable
      ref="$table"
      v-model:query-items="queryItems"
      :columns="columns"
      :get-data="api.getBaoXiao"
    >
      <template #queryBar>
        <QueryBarItem label="报销单号" :label-width="80">
          <NInput
            v-model:value="queryItems.no"
            clearable
            type="text"
            style="width: 140px"
            placeholder="请输入报销单号"
            @keypress.enter="$table?.handleSearch()"
          />
        </QueryBarItem>
        <QueryBarItem label="员工姓名" :label-width="80">
          <NSelect
            v-model:value="queryItems.user_id"
            style="width: 120px"
            :options="data.users"
            clearable
            placeholder="请选择员工"
          />
        </QueryBarItem>

        <QueryBarItem label="申请时间" :label-width="70">
          <NDatePicker
            v-model:value="datetimeRange"
            type="datetimerange"
            clearable
            placeholder="请选择时间范围"
            @update:value="handleDateRangeChange"
          />
        </QueryBarItem>

        <QueryBarItem label="状态" :label-width="40">
          <NSelect
            v-model:value="queryItems.status"
            style="width: 120px"
            :options="data.state_option"
            clearable
            placeholder="全部"
          />
        </QueryBarItem>
      </template>
    </CrudTable>

     <!-- 新增/编辑 弹窗 -->
    <CrudModal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :loading="modalLoading"
      @save="handleSave"
      style="width: 900px;"
    >
      <NForm
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
        :rules="validateAddUser"
      >
        <n-alert :title="'单号:'+modalForm.no" type="success" style="margin-bottom: 10px">
          <div>
              申请员工&nbsp;:&nbsp;<n-tag style="margin-right: 10px;padding: 5px 10px">{{modalForm.bm_name}}-{{modalForm.user_name}}</n-tag>
              报销金额&nbsp;:&nbsp;<n-tag style="margin-right: 10px;padding: 5px 10px">¥{{modalForm.price}}</n-tag>
              发票金额&nbsp;:&nbsp;<n-tag style="margin-right: 10px;padding: 5px 10px">¥{{modalForm.fp_price}}</n-tag>
              差额&nbsp;:&nbsp;<n-tag style="margin-right: 10px;padding: 5px 10px">¥{{modalForm.re_price}}</n-tag>
          </div>
          <div style="margin-top: 10px">
              申请时间&nbsp;:&nbsp;<n-tag style="margin-right: 10px;padding: 5px 10px">{{modalForm.created_at}}</n-tag>
              备注&nbsp;:&nbsp;<n-tag style="padding: 5px 10px">{{modalForm.desc}}</n-tag>
          </div>
        </n-alert>
        <n-divider dashed>
          报销明细
        </n-divider>
          <n-data-table :columns="details_columns" :data="modalForm.details" striped :max-height="220" size="small"/>
          <n-divider dashed>
          报销审核
        </n-divider>

        <n-radio-group v-model:value="modalForm.status" name="radiogroup" :default-value="0">
          <n-space>
            <n-radio v-for="item in data.check_option" :key="item.value" :value="item.value">
              {{ item.label }}
            </n-radio>
          </n-space>
        </n-radio-group>

        <NFormItem label="" path="bh_desc" style="margin-top: 10px" v-if="modalForm.status===2">
          <NInput
                  type="textarea"
                  style="width: 100%"
                  v-model:value="modalForm.bh_desc"
                  clearable
                  placeholder="请输入驳回原因"
                />
        </NFormItem>



      </NForm>
    </CrudModal>
  </CommonPage>
</template>
